package com.dwj.auto.comment.common.security;

import com.dwj.auto.comment.common.response.Response;
import com.dwj.auto.comment.dao.entity.User;
import com.dwj.auto.comment.service.IUserRoleService;
import com.dwj.auto.comment.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.LockedException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Component;

import java.util.HashSet;
import java.util.Set;

/**
 * @author: dangweijian
 * @description: 登录校验处理类
 * @create: 2020-07-09 14:39
 **/
@Component
public class UserAuthenticationProvider implements AuthenticationProvider {

    @Autowired
    private IUserService userService;
    @Autowired
    private IUserRoleService userRoleService;
    @Autowired
    private BCryptPasswordEncoder bCryptPasswordEncoder;

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        String userName = (String) authentication.getPrincipal();
        String password = (String) authentication.getCredentials();
        Response<User> response = userService.getByUsername(userName);
        if (response == null || response.getData() == null) {
            throw new UsernameNotFoundException("用户名或密码错误");
        }
        User user = response.getData();
        //账号已冻结
        if(user.getStatus() == 1){
            throw new LockedException("账号已冻结");
        }
        if(!bCryptPasswordEncoder.matches(password, user.getPassword())){
            throw new BadCredentialsException("用户名或密码错误");
        }
        // TODO 获取用户角色权限
        Set<SimpleGrantedAuthority> authorities = new HashSet<>();
        return new UsernamePasswordAuthenticationToken(response.getData(), password, authorities);
    }

    @Override
    public boolean supports(Class<?> aClass) {
        return UsernamePasswordAuthenticationToken.class.isAssignableFrom(aClass);
    }
}
